package com.hx.util.httpclient;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang.StringUtils;

public class HttpClientUtils {
	HttpClient client = null;

	/**
	 * httpClient  get 请求
	 * @param httpUrl 请求地址
	 * @param para    请求参数 参数格式  name=xujin&passwd=xujin
	 * @return        返回的String
	 * @throws Exception
	 */
	public String httpClientGet(String httpUrl, String params,String code) throws Exception {
		client = new HttpClient();
		HttpMethod method = new GetMethod(httpUrl);
		if(StringUtils.isBlank(code)){
		method.setRequestHeader("Content-Type", "text/html;charset=utf-8");
		}else{
		method.setRequestHeader("Content-Type", "text/html;charset="+code+"");
		}
		method.setQueryString(params);
		client.executeMethod(method);
		if (method.getStatusCode() == HttpStatus.SC_OK) {
			String response = method.getResponseBodyAsString();
			return response;
		}
		method.releaseConnection();
		return null;
	}
	
	public String httpClientPost(String httpUrl, String params,String code) throws Exception {
		client = new HttpClient();
		PostMethod method = new PostMethod(httpUrl);
		if(StringUtils.isBlank(code)){
			method.setRequestHeader("Content-Type", "text/html;charset=utf-8");
		}else{
		   method.setRequestHeader("Content-Type", "text/html;charset="+code+"");
		}
		method.setQueryString(params);
		client.executeMethod(method);
		if (method.getStatusCode() == HttpStatus.SC_OK) {
			String response = method.getResponseBodyAsString();
			return response;
		}
		method.releaseConnection();
		return null;
	}
	

	public static void main(String[] args) throws Exception {
		String url = "http://www.baidu.com";
		HttpClientUtils test=new HttpClientUtils();
		System.out.println(test.httpClientGet(url,"", null));
	}

}
